package network;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

public class TcpEchoClient {
    private Socket socket=null;
    public TcpEchoClient(String ServerIP, int ServerPort) throws IOException {
        //由于tcp是有连接的，所以会自动保存这里的ip和端口号
        socket=new Socket(ServerIP,ServerPort);
    }

    public void start(){
        System.out.println("客户端启动了");
        try (InputStream inputStream=socket.getInputStream();
             OutputStream outputStream= socket.getOutputStream()){
            Scanner scannerConsole=new Scanner(System.in);
            Scanner scannernetwork=new Scanner(inputStream);
            PrintWriter writer=new PrintWriter(outputStream);
            while (true){
                System.out.println("->");
                if(!scannerConsole.hasNext()){
                    break;
                }
                String request=scannerConsole.next();
                //发送数据用到写的操作
                writer.println(request);
                writer.flush();
                //接收数据
                String response=scannernetwork.next();

                System.out.println(response);
            }

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) throws IOException {
        TcpEchoClient client=new TcpEchoClient("127.0.0.1",3456);
        client.start();
    }

}
